package com.cci.kangdao.controller;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.crmapi.CRMServiceApi;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.dao.AllServiceStationDao;
import com.cci.kangdao.dao.WorkOrderSynchroTMapper;
import com.cci.kangdao.dao.WorkOrderTDao;
import com.cci.kangdao.dao.model.WorkOrderSynchroT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CRMPlatformService;
import com.cci.kangdao.service.WorkOrderIndividualCasesService;
import com.cci.kangdao.task.*;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author William Du
 * @date 2019/12/6
 */
@Controller
public class AdminController {
    private Logger log = Logger.getLogger(this.getClass().getName());
    @Resource
    private CRMPlatformService crmPlatformService;

    @Resource
    private CRMServiceApi crmServiceApi;

    @Resource
    private SyncServiceTechnicianMsgToCRMTask syncServiceTechnicianMsgToCRMTask;

    @Autowired
    private AllServiceStationDao allServiceStationDao;

    @Resource
    private UpdateEsnAppPowerTypeTask updateEsnAppPowerTypeTask;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Resource
    private WorkOrderSynchroTMapper workOrderSynchroTMapper;
    @Resource
    private WorkOrderTDao workOrderTDao;
    @Resource
    private RemindTask remindTask;
    @Resource
    private DBUWorkOrderTask dbuWorkOrderTask;
    @Resource
    private SynchronizationWeChatDataTask synchronizationWeChatDataTask;
    @Resource
    private FeedBackDealTask feedBackDealTask;
    @Resource
    private ServiceAgreementTask serviceAgreementTask;
    @Resource
    private EscalationOrderTask escalationOrderTask;
    @Resource
    private ExceptionDataSyncCrmTask exceptionDataSyncCrmTask;
    @Resource
    private FieldServiceTask fieldServiceTask;
    @Resource
    private GMRecordCheckTask gmrecordCheckTask;
    @Resource
    private CampaignTaskSchedule campaignTaskSchedule;

    @Resource
    private WorkOrderIndividualCasesService workOrderIndividualCasesService;

    @Value("${spring.profiles.active}")
    private String active;

    @RequestMapping("/retryExceptionOrder.aspx")
    public String retryExceptionOrder(HttpServletResponse response) {
        try {
            crmPlatformService.syncExceptionalOrderInfoToCRM(false);
            crmServiceApi.retryExceptionSync();

            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }



    @RequestMapping("/retryExceptionDataSyncCrm.aspx")
    public String retryExceptionDataSyncCrm(HttpServletResponse response, HttpServletRequest request) {
        try {
            Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
            map.put("response", response);
            map.put("request", request);
            crmPlatformService.retryExceptionDataSyncCrm(map);
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }


    @RequestMapping("/syncServiceTechnicianMsgToCRMTask.aspx")
    public String syncServiceTechnicianMsgToCRMTask(HttpServletResponse response) {
        try {
            syncServiceTechnicianMsgToCRMTask.getServiceTechnicianMsgList();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    @RequestMapping("/appGet.aspx")
    public void appGet(String token) {
        NotifyUtil.push2Single(token, "康明斯天远", "康明斯天远test", 2, "123");
//        NotifyUtil.pushMessageToApp("广播测试",2,"广播测试");

    }

    @RequestMapping("/phone.aspx")
    public void phone(String phone) {
        List<Map<String, Object>> allServiceStationInCSHNew = allServiceStationDao.getAllServiceStationInCSHNew(phone);
    }


    @RequestMapping("/batchUpdateEsnAppPowerType.aspx")
    public String batchUpdateEsnAppPowerType(String param,HttpServletResponse response) {
        try {
            updateEsnAppPowerTypeTask.publicTask(param);
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    @RequestMapping("/test.aspx")
    public void test(HttpServletResponse response) throws IOException {
        Map<String,String> map = new HashMap<>();
        String commitTime = PropertiesUtil.getProperties("git.properties","git.commit.time");
        String buildTime = PropertiesUtil.getProperties("git.properties","git.build.time");
        String message = PropertiesUtil.getProperties("git.properties","git.commit.message.short");
        String branch = PropertiesUtil.getProperties("git.properties","git.branch");
        map.put("active",active);
        map.put("branch",branch);
        map.put("commitTime",commitTime);
        map.put("buildTime",buildTime);
        map.put("message",message);
        response.getWriter().print(map);
    }

    /**
     * 从redis中获取保存到数据库
     * @param response
     * @return
     */
    @RequestMapping("/getRedisToTable.aspx")
    public String getRedisToTable(HttpServletResponse response) {
        try {
            //dbu和DCEC工单信息
            List<Map<String, Object>> exceptionalOrderInfos = redisClientUtils.getObjectList(CRMServiceConst.KEY_ORDERINFO_EXCEPTIONAL_APP);
            //dbu工单状态
            List<Map<String, Object>> exceptionalOrderStatus = redisClientUtils.getObjectList(CRMServiceConst.KEY_ORDERSTATUS_EXCEPTIONAL_APP);
            if(CollectionUtils.isNotEmpty(exceptionalOrderInfos)){
                for (int i = 0; i < exceptionalOrderInfos.size(); i++) {
                    Map<String, Object> exceptionMap = exceptionalOrderInfos.get(i);
                    String createTime = (String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
                    String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> params = (Map<String, Object>) cloneMap.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
                    String appOrderNo = params.get("orderNo").toString();
                    WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(appOrderNo);
                    if(null != workOrderT){
                        WorkOrderSynchroT record = new WorkOrderSynchroT();
                        record.setOrderNo(appOrderNo);
                        record.setChannelName(channelName);
                        record.setProcessStatus(1);
                        record.setOrderInfo(JSON.toJSONString(params));
                        record.setSyncStatus(0);
                        record.setOrderId(workOrderT.getId());
                        record.setOrderNoCrm(workOrderT.getOrderNoCrm());
                        record.setFlag(0);
                        record.setCreater(-1L);
                        record.setCreateTime(createTime);
                        int count = workOrderSynchroTMapper.insert(record);
                    }
                }
            }

            if(CollectionUtils.isNotEmpty(exceptionalOrderStatus)) {
                for (int i = 0; i < exceptionalOrderStatus.size(); i++) {
                    Map<String, Object> exceptionMap = exceptionalOrderStatus.get(i);
                    String createTime = (String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
                    String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> params = (Map<String, Object>) cloneMap.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
                    String appOrderNo = params.get("orderNo").toString();
                    WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(appOrderNo);
                    if (null != workOrderT) {
                        WorkOrderSynchroT record = new WorkOrderSynchroT();
                        record.setOrderNo(appOrderNo);
                        record.setChannelName(channelName);
                        record.setProcessStatus(MapUtils.getInteger(params, "billStatus"));
                        record.setOrderInfo(JSON.toJSONString(params));
                        record.setSyncStatus(0);
                        record.setOrderId(workOrderT.getId());
                        record.setOrderNoCrm(workOrderT.getOrderNoCrm());
                        record.setFlag(0);
                        record.setCreater(-1L);
                        record.setCreateTime(createTime);
                        int count = workOrderSynchroTMapper.insert(record);
                    }
                }
            }
            //XCEC工单信息
            List<Map<String, Object>> exceptionalOrderInfosXCEC = redisClientUtils.getObjectList(CRMServiceConst.KEY_ORDERINFO_EXCEPTIONAL_APP_XCEC);
            //XCEC工单状态
            List<String> xcec_keys = redisClientUtils.keys(CRMServiceConst.KEY_XCEC_ORDERSTATUS_APP + "*");
            if(CollectionUtils.isNotEmpty(exceptionalOrderInfosXCEC)){
                for (int i = 0; i < exceptionalOrderInfosXCEC.size(); i++) {
                    Map<String, Object> exceptionMap = exceptionalOrderInfosXCEC.get(i);
                    String createTime = (String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
                    String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
                    Map<String, Object> params = (Map<String, Object>) cloneMap.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
                    String appOrderNo = params.get("orderNo").toString();
                    WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(appOrderNo);
                    if(null != workOrderT){
                        WorkOrderSynchroT record = new WorkOrderSynchroT();
                        record.setOrderNo(appOrderNo);
                        record.setChannelName(channelName);
                        record.setProcessStatus(1);
                        record.setOrderInfo(JSON.toJSONString(params));
                        record.setSyncStatus(0);
                        record.setOrderId(workOrderT.getId());
                        record.setOrderNoCrm(workOrderT.getOrderNoCrm());
                        record.setFlag(0);
                        record.setCreater(-1L);
                        record.setCreateTime(createTime);
                        int count = workOrderSynchroTMapper.insert(record);
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(xcec_keys)){
                for (int index = 0; index < xcec_keys.size(); index++) {
                    List<Map<String, Object>> xcecOrderExList = redisClientUtils.getObjectList(xcec_keys.get(index));
                    if (xcecOrderExList != null && xcecOrderExList.size() > 0) {
                        for (int i = 0; i < xcecOrderExList.size(); i++) {
                            Map<String, Object> exceptionMap = xcecOrderExList.get(i);
                            String createTime = (String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP);
                            Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
                            String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
                            Map<String, Object> params = (Map<String, Object>) cloneMap.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
                            String appOrderNo = params.get("orderNo").toString();
                            WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(appOrderNo);
                            if(null != workOrderT){
                                WorkOrderSynchroT record = new WorkOrderSynchroT();
                                record.setOrderNo(appOrderNo);
                                record.setChannelName(channelName);
                                record.setProcessStatus(MapUtils.getInteger(params, "billStatus"));
                                record.setOrderInfo(JSON.toJSONString(params));
                                record.setSyncStatus(0);
                                record.setOrderId(workOrderT.getId());
                                record.setOrderNoCrm(workOrderT.getOrderNoCrm());
                                record.setFlag(0);
                                record.setCreater(-1L);
                                record.setCreateTime(createTime);
                                int count = workOrderSynchroTMapper.insert(record);
                            }
                        }
                    }
                }
            }

            List<String> dcec_keys = redisClientUtils.keys(CRMServiceConst.KEY_DCEC_ORDERSTATUS_APP + "*");
            if(CollectionUtils.isNotEmpty(dcec_keys)){
                for (int index = 0; index < dcec_keys.size(); index++) {
                    List<Map<String, Object>> dcecOrderExList = redisClientUtils.getObjectList(dcec_keys.get(index));
                    if (dcecOrderExList != null && dcecOrderExList.size() > 0) {
                        for (int i = 0; i < dcecOrderExList.size(); i++) {
                            Map<String, Object> exceptionMap = dcecOrderExList.get(i);
                            String createTime = (String) exceptionMap.get(CRMServiceConst.CURRENTTIME_INTERFACE_EXCEPTIONAL_APP);
                            Map<String, Object> cloneMap = (Map<String, Object>) BeanUtils.deepClone(exceptionMap);
                            String channelName = (String) cloneMap.get(CRMServiceConst.CHANNEL_INTERFACE_EXCEPTIONAL_APP);
                            Map<String, Object> params = (Map<String, Object>) cloneMap.get(CRMServiceConst.DATA_CRMPARAMS_EXCEPTIONAL_APP);
                            String appOrderNo = params.get("orderNo").toString();
                            WorkOrderT workOrderT = workOrderTDao.selectWorkOrderByOrderNo(appOrderNo);
                            if(null != workOrderT){
                                WorkOrderSynchroT record = new WorkOrderSynchroT();
                                record.setOrderNo(appOrderNo);
                                record.setChannelName(channelName);
                                record.setProcessStatus(MapUtils.getInteger(params, "billStatus"));
                                record.setOrderInfo(JSON.toJSONString(params));
                                record.setSyncStatus(0);
                                record.setOrderId(workOrderT.getId());
                                record.setOrderNoCrm(workOrderT.getOrderNoCrm());
                                record.setFlag(0);
                                record.setCreater(-1L);
                                record.setCreateTime(createTime);
                                int count = workOrderSynchroTMapper.insert(record);
                            }
                        }
                    }
                }
            }

            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }


    /**
     * DBU超时工单定时任务(一分钟)
     * @param response
     * @return
     */
    @RequestMapping("/workOrderTask.aspx")
    public String workOrderTask(HttpServletResponse response) {
        try {
            dbuWorkOrderTask.workOrderTask();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 服务工单所有的定时重传(一小时)
     * @param response
     * @return
     */
    @RequestMapping("/workOrderSynchronization.aspx")
    public String workOrderSynchronization(HttpServletResponse response) {
        try {
            remindTask.workOrderExceptionSynchronization();
            //同步 服务rv  超时原因
            workOrderIndividualCasesService.syncWorkOrderReason();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }


    /**
     * campaign任务所有的定时重传(一小时)
     * @param response
     * @return
     */
    @RequestMapping("/campaignTaskRetry.aspx")
    public String campaignTaskRetry(HttpServletResponse response) {
        try {
            campaignTaskSchedule.campaignTaskSchedule();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 超时各角色超时工单提醒,一分钟执行一次(0 0/1 * * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/taskCycle.aspx")
    public String taskCycle(HttpServletResponse response) {
        try {
            remindTask.taskCycle();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 定时更新用户已绑定设备的发动机基础数据(0 5 16 26 * ?)
     * @param response
     * @return
     */
    @RequestMapping("/updateEsnAppPowerType.aspx")
    public String updateEsnAppPowerType(HttpServletResponse response) {
        try {
            updateEsnAppPowerTypeTask.batchUpdateEsnAppPowerType();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 每天每隔一小时同步微信数据到数据库
     * @param response
     * @return
     */
    @RequestMapping("/synchronizationWeChatData.aspx")
    public String synchronizationWeChatData(HttpServletResponse response) {
        try {
            synchronizationWeChatDataTask.synchronizationWeChatData();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 每天八点发送e路康明斯工单处理提醒邮件
     * @param response
     * @return
     */
    @RequestMapping("/dealFeedBack.aspx")
    public String dealFeedBack(HttpServletResponse response) {
        try {
            feedBackDealTask.dealFeedBack();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 每天八点更新协议状态
     * @param response
     * @return
     */
    @RequestMapping("/serviceAgreement.aspx")
    public String serviceAgreement(HttpServletResponse response) {
        try {
            serviceAgreementTask.dealFeedBack();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 处理redis中存储的升级工单催单记录(0 0 17 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/escalationOrderTask.aspx")
    public String escalationOrderTask(HttpServletResponse response) {
        try {
            escalationOrderTask.workOrderTask();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 同步主动升级详情信息至CRM： 每小时执行一次
     * @param response
     * @return
     */
    @RequestMapping("/syncESOrderDetail.aspx")
    public String syncESOrderDetail(HttpServletResponse response) {
        try {
            escalationOrderTask.syncESOrderDetail();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 同步srt确认维修数据到crm(0 30 3,15 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/exceptionDataSyncCrm.aspx")
    public String exceptionDataSyncCrm(HttpServletResponse response) {
        try {
            exceptionDataSyncCrmTask.exceptionDataSyncCrm();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 异步同步crm(0 0 0/1 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/syncRetry.aspx")
    public String syncRetry(HttpServletResponse response) {
        try {
            fieldServiceTask.workOrderExceptionSynchronization();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * GMA超时提醒(0 30 0 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/overTimeNotice.aspx")
    public String overTimeNotice(HttpServletResponse response) {
        try {
            gmrecordCheckTask.overTimeNotice();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * GMA权限到期状态变更(0 30 15 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/setApplyOverTime.aspx")
    public String setApplyOverTime(HttpServletResponse response) {
        try {
            gmrecordCheckTask.setApplyOverTime();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 每日刷新的未审批的GM申请记录(0 0 0 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/setGMDailyStatus.aspx")
    public String setGMDailyStatus(HttpServletResponse response) {
        try {
            gmrecordCheckTask.setGMDailyStatus();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 每天23点同步服务技师信息到CRM(0 0 15 * * ?)
     * @param response
     * @return
     */
    @RequestMapping("/syncServiceTechnician.aspx")
    public String syncServiceTechnician(HttpServletResponse response) {
        try {
            syncServiceTechnicianMsgToCRMTask.syncServiceTechnicianMsgToCRM();
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

}
